package com.ease.plugin.traits {
	import com.ease.core.plugin.ResourceBase;
	import com.ease.plugin.events.LoaderEvent;
	import com.ease.plugin.utils.PluginStrings;

	import flash.errors.IllegalOperationError;
	import flash.events.EventDispatcher;

	public class LoaderBase extends EventDispatcher {
		public function canHandleResource(resource:ResourceBase):Boolean {
			return false;
		}

		public final function load(loadTrait:LoadTrait):void {
			validateLoad(loadTrait);
			executeLoad(loadTrait);
		}

		public final function unload(loadTrait:LoadTrait):void {
			validateUnload(loadTrait);
			executeUnload(loadTrait);
		}

		protected function executeLoad(loadTrait:LoadTrait):void {
		}

		protected function executeUnload(loadTrait:LoadTrait):void {
		}

		protected final function updateLoadTrait(loadTrait:LoadTrait, newState:String):void {
			if (newState != loadTrait.loadState) {
				var oldState:String = loadTrait.loadState;

				dispatchEvent
					( new LoaderEvent
						( LoaderEvent.LOAD_STATE_CHANGE
						, false
						, false
						, this
						, loadTrait
						, oldState
						, newState
						)
					);
			}
		}

		/**
		 * Validates that the given LoadTrait can be loaded.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10
		 *  @playerversion AIR 1.5
		 */
		private function validateLoad(loadTrait:LoadTrait):void {
			if (loadTrait == null) {
				throw new IllegalOperationError(PluginStrings.getString(PluginStrings.NULL_PARAM));
			}
			if (loadTrait.loadState == LoadState.READY) {
				throw new IllegalOperationError(PluginStrings.getString(PluginStrings.ALREADY_READY));
			}
			if (loadTrait.loadState == LoadState.LOADING) {
				throw new IllegalOperationError(PluginStrings.getString(PluginStrings.ALREADY_LOADING));
			}
			if (canHandleResource(loadTrait.resource) == false) {
				throw new IllegalOperationError(PluginStrings.getString(PluginStrings.LOADER_CANT_HANDLE_RESOURCE));
			}
		}


		/**
		 * Validates that the given LoadTrait can be unloaded.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10
		 *  @playerversion AIR 1.5
		 */
		private function validateUnload(loadTrait:LoadTrait):void {
			if (loadTrait == null) {
				throw new IllegalOperationError(PluginStrings.getString(PluginStrings.NULL_PARAM));
			}
			if (loadTrait.loadState == LoadState.UNLOADING) {
				throw new IllegalOperationError(PluginStrings.getString(PluginStrings.ALREADY_UNLOADING));
			}
			if (loadTrait.loadState == LoadState.UNINITIALIZED) {
				throw new IllegalOperationError(PluginStrings.getString(PluginStrings.ALREADY_UNLOADED));
			}
			if (canHandleResource(loadTrait.resource) == false) {
				throw new IllegalOperationError(PluginStrings.getString(PluginStrings.LOADER_CANT_HANDLE_RESOURCE));
			}
		}
	}
}